# -*- coding: utf-8 -*-
'''
@文件    :asyncio.py
@说明    :
@时间    :2025/08/26 14:49:16
@作者    :浪晋
@版本    :1.0
'''

from typing import List, Dict, Tuple
from tortoise import Tortoise
from tortoise.transactions import in_transaction

class AsyncORMDB:
    def __init__(self, config: Dict):
        self.config = config
    
    async def query(self, sql: str, args: List = []) -> List[Dict]:
        """返回字典格式的结果列表"""
        async with in_transaction("default") as conn:
            return await conn.execute_query_dict(sql, args)

    async def execute(self, sql: str, args: List = []) -> Tuple[int, List]:
        """
        返回受影响的行数以及查询结果
        """
        async with in_transaction("default") as conn:
            return await conn.execute_query(sql, args)

    async def insert(self, sql: str, args: List = []) -> int:
        """
        返回新增的主键Id
        """
        async with in_transaction("default") as conn:
            return await conn.execute_insert(sql, args)

    async def startup(self):
        await Tortoise.init(config=self.config)
        tables = await self.query("show tables;")
        if not tables:
            await Tortoise.generate_schemas(safe=True)

    async def shutdown(self):
        await Tortoise.close_connections()

